import os

from django import http
from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from alipay import AliPay
# Create your views here.
from django.views import View

from apps.orders.models import OrderInfo
from apps.payment.models import Payment
from utils.response_code import RETCODE


class PaySuccessView(LoginRequiredMixin,View):
    def get(self,request):
        #接收参数
        params_query_dict = request.GET
        #类型转化 转成dict()
        data = params_query_dict.dict()

        signature = data.pop('sign')
        #支付宝的二次校验
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # app_notify_url 支付宝的异步通知
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem'),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_public_key.pem'),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )
        # 校验这个重定向是否是alipay重定向过来的
        success = alipay.verify(data,signature)
        if success:
            #读取order_id
            order_id = data.get('out_trade_no')
            trade_id = data.get('trade_no')
            Payment.objects.create(
                order_id = order_id,
                trade_id = trade_id
            )

            # 6. 修改订单的状态                             ---待支付--->待评价
            OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(
                status=OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT']
            )

            # 7. 返回响应
            context = {
                'trade_id': trade_id
            }
        else:
            context = {
                'trade_id': "交易失败 支付失败了!"
            }
        return render(request, 'pay_success.html', context)

class PaymentView(LoginRequiredMixin,View):
    def get(self,request,order_id):
        #检验订单
        try:
            order = OrderInfo.objects.get(order_id = order_id)
        except:
            return http.HttpResponseForbidden("订单无效")

        #生成alipay支付对象
        # ALIPAY_APPID = '2016101300673828'
        # ALIPAY_DEBUG = True
        # ALIPAY_URL = 'https://openapi.alipaydev.com/gateway.do'
        # ALIPAY_RETURN_URL = 'http://www.meiduo.site:8000/payment/status/'
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,    #app_notify_url 支付宝的异步通知
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),'keys/app_private_key.pem'),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),'keys/app_public_key.pem'),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )

        #讲必传参数  进行 加密 拼接 url
        order_str = alipay.api_alipay_trade_page_pay(
            subject="美多商城%s" % order_id,
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            return_url=settings.ALIPAY_RETURN_URL
        )
        #返回前端
        alipay_url = settings.ALIPAY_URL + '?' + order_str

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'alipay_url': alipay_url})


